//
//  whackViewController.m
//  whack
//
//  Created by tmadar on 11/2/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "whackViewController.h"
#include <stdlib.h>
#import <time.h>
#import <AudioToolbox/AudioToolbox.h>

@implementation whackViewController

@synthesize Counter;
@synthesize mole1;
@synthesize mole2;
@synthesize mole3;
@synthesize mole4;
@synthesize mole5;
@synthesize mole6;
@synthesize mole7;
@synthesize mole8;
@synthesize mole9;
@synthesize CurrentPoint;
@synthesize ParPoints;
@synthesize levelVal;

int points;
int parValue;
int levelnum;
int maxSec;
double t;
double moveDownMod;
NSInteger old_minutes;
NSInteger old_hours;



- (void)dealloc
{
    [Counter release];
    [mole1 release];
    [mole2 release];
    [mole3 release];
    [mole4 release];
    [mole5 release];
    [mole6 release];
    [mole7 release];
    [mole8 release];
    [mole9 release];
    [CurrentPoint release];
    [ParPoints release];
    [levelVal release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    
    [super viewDidLoad];
}


- (void)viewDidUnload
{
    [self setCounter:nil];
    [self setMole1:nil];
    [self setMole2:nil];
    [self setMole3:nil];
    [self setMole4:nil];
    [self setMole5:nil];
    [self setMole6:nil];
    [self setMole7:nil];
    [self setMole8:nil];
    [self setMole9:nil];
    [self setCurrentPoint:nil];
    [self setParPoints:nil];
    [self setLevelVal:nil];
    [super viewDidUnload];

}

/*- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}*/

-(IBAction)readExitButtonPressed {
    levelnum = 1;
   
    t = 1;
    
    [stopWatchTimer invalidate];
    stopWatchTimer = nil;
    
    NSString *x1=[NSString stringWithFormat:@"Level: %d", levelnum];
    levelVal.text = x1;
    
    maxSec = 30;
    
    startDate = [[NSDate date]retain];
    
    //stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0 target: self selector: @selector(updateTimer) userInfo:nil repeats:YES];
    
    [self highScore];
    
    [self updateTimer];
    

    [self.parentViewController dismissModalViewControllerAnimated: YES];
}

-(BOOL)highScore
{
    
    NSUserDefaults *defaulted = [NSUserDefaults standardUserDefaults];
    NSArray *stuff;
    stuff = [defaulted arrayForKey:@"highScores"];
    BOOL newScore = NO;
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstRun"]) {
        
        [[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"0", @"0", @"0", nil] forKey:@"highScores"];
        
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstRun"];
    }

    if(points > [[stuff objectAtIndex:2] intValue] ){
        [[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects: [stuff objectAtIndex:1], [stuff objectAtIndex:2],[NSString stringWithFormat:@"%d",points], nil] forKey:@"highScores"];
        newScore = YES;

    }
    else if(points > [[stuff objectAtIndex:1] intValue] ){
        [[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects: [stuff objectAtIndex:1], [NSString stringWithFormat:@"%d",points],[stuff objectAtIndex:2], nil] forKey:@"highScores"];
        newScore = YES;
    }
    else if(points > [[stuff objectAtIndex:0] intValue] ){
        [[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:  [NSString stringWithFormat:@"%d",points],[stuff objectAtIndex:1],[stuff objectAtIndex:2], nil] forKey:@"highScores"];
        newScore = YES;
    }

    return newScore;
}

- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{
    return ((interfaceOrientation == UIInterfaceOrientationLandscapeLeft) || (interfaceOrientation == UIInterfaceOrientationLandscapeRight));
}

-(void)viewDidAppear:(BOOL)animated
{
    parValue = 40;
    points = 0;
    maxSec = 30;
    levelnum = 1;
    t = 1;
    NSString *x1=[NSString stringWithFormat:@"Level: %d", levelnum];
    levelVal.text = x1;
    
    startDate = [[NSDate date]retain];
    
    NSDate *currentDate = [NSDate date];
    NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
    NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    NSDateFormatter *dateFormatter =[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"s"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:(kCFCalendarUnitHour | kCFCalendarUnitMinute | kCFCalendarUnitSecond) fromDate:timerDate];
    old_hours = [components hour];
    old_minutes = [components minute];
        
    stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0 target: self selector: @selector(updateTimer) userInfo:nil repeats:YES];
    
    [self moveUp:nil finished:nil context:nil];
    
    
}

- (void) updateTimer
{   
    
    NSDate *currentDate = [NSDate date];
    NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
    NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    NSDateFormatter *dateFormatter =[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"s"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
 
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:(kCFCalendarUnitHour | kCFCalendarUnitMinute | kCFCalendarUnitSecond) fromDate:timerDate];
    NSInteger current_hours = [components hour];
    NSInteger current_minutes = [components minute];
    NSInteger seconds = [components second];
    if(current_minutes > old_minutes)
    {
        seconds += 60*(current_minutes-old_minutes);
    }
    if(current_hours > old_hours)
    {
        seconds += 360*(current_hours-old_hours);
    }
    NSInteger timeLeft = maxSec - seconds;
    NSString *timeString=[NSString stringWithFormat:@"%d", timeLeft];
    Counter.text = timeString;
    [dateFormatter release];
    
    if(timeLeft == 0)
    {
        NSString* plistPath = nil;
        NSFileManager* manager = [NSFileManager defaultManager];
        if (plistPath == [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"Contents/HighScore.plist"]) 
        {
            if ([manager isWritableFileAtPath:plistPath]) 
            {
                NSMutableDictionary* infoDict = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];
                [infoDict setObject:scores forKey:@"Scores"];
                [infoDict writeToFile:plistPath atomically:NO];
                [manager changeFileAttributes:[NSDictionary dictionaryWithObject:[NSDate date] forKey:NSFileModificationDate] atPath: [[NSBundle mainBundle] bundlePath]];
            }
        }
                
       // [self highScore];
        
        //[self.parentViewController dismissModalViewControllerAnimated: YES];
        [self readExitButtonPressed];
    }
    
}

- (void)moveUp:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
    
    srand(time(NULL));
    int r = (rand() % 9)+1;
    int r2 = (rand() % 9)+1;
    int r3=0;
    int r4=0;
    
    if(points >= parValue)
    {
        parValue += 40 + (levelnum * 5);
        t = pow(.7,levelnum);
        levelnum++;
        maxSec +=10;
    }
    
        
    if(levelnum>3)
    {
        r3 = (rand() % 9)+1;
    }
    
    if(levelnum>8)
    {
        r4 = (rand() % 9)+1;
    }
   
    
    NSString *p=[NSString stringWithFormat:@"%d", parValue];
    ParPoints.text = p;
    
    NSString *x1=[NSString stringWithFormat:@"Level: %d", levelnum];
    levelVal.text = x1;

    
    [UIView beginAnimations:nil context:nil];
    
    [UIView setAnimationDuration:.25*t];
    
    [UIView setAnimationDelay:0.7];
    
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    
    [UIView setAnimationDelegate:self];
    
    [UIView setAnimationDidStopSelector:@selector(moveDown:finished:context:)];
    

    mole1active = NO;
    mole2active = NO;
    mole3active = NO;
    mole4active = NO;
    mole5active = NO;
    mole6active = NO;
    mole7active = NO;
    mole8active = NO;
    mole9active = NO;
    
    if(r==1 || r2==1 || r3 ==1 || r4 == 1)
    {
        mole1.alpha = 1.0;
        mole1.center = CGPointMake(58, 41);

        mole1active = YES;
      
    }
    if(r==2|| r2==2 || r3 ==2 || r4==2 )
    {
        mole2.alpha = 1.0;
        mole2.center = CGPointMake(148, 41);
    
        mole2active = YES;
        
    }
    if(r==3|| r2==3 || r3==3 || r4==3 )
    {
        mole3.alpha = 1.0;
        mole3.center = CGPointMake(240, 41);

        mole3active = YES;
      
    }
    if(r==4|| r2==4 || r3==4 || r4==4 )
    {
        mole4.alpha = 1.0;
        mole4.center = CGPointMake(332, 41);
    
        mole4active = YES;
      
    }
    if(r==5|| r2==5 || r3==5 || r4==5 )
    {
        mole5.alpha = 1.0;
        mole5.center = CGPointMake(422, 41);
    
        mole5active = YES;
       
    }
    if(r==6|| r2==6 || r3==6 || r4==6 )
    {
        mole6.alpha = 1.0;
        mole6.center = CGPointMake(102, 120);

        mole6active = YES;
       
    }
    if(r==7|| r2==7 || r3==7 || r4==7 )
    {
        mole7.alpha = 1.0;
        mole7.center = CGPointMake(198, 120);

        mole7active = YES;
      
    }
    if(r==8|| r2==8 || r3==8 || r4==8 )
    {
        mole8.alpha = 1.0;
        mole8.center = CGPointMake(291, 120);

        mole8active = YES;
      
    }
    if(r==9|| r2==9 || r3==9 || r4==9 )
    {
        mole9.alpha = 1.0;
        mole9.center = CGPointMake(379, 120);

        mole9active = YES;
     
    }
    [UIView commitAnimations];
    
    
    
}



- (void)moveDown:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
    
    if(levelnum>5)
    {
        moveDownMod = pow(.8,levelnum);
    }


    
    [UIView beginAnimations:nil context:nil];
    
    [UIView setAnimationDuration:.25*moveDownMod];
    
    [UIView setAnimationDelay:0.5];
    
    if(levelnum>5)
    {
        [UIView setAnimationDelay:0.3];
    }
    
    if(levelnum>10)
       {
           [UIView setAnimationDelay:0.1];
       }
    
    [UIView setAnimationDelegate:self];
    
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    
    [UIView setAnimationDidStopSelector:@selector(moveUp:finished:context:)];
    
    mole1.center = CGPointMake(58, 71);
    
    [UIView setAnimationDuration:.3];
    
    mole2.center = CGPointMake(148, 71);
    
    [UIView setAnimationDuration:.3];
    
    mole3.center = CGPointMake(240, 71);
    
    [UIView setAnimationDuration:.3];
    
    mole4.center = CGPointMake(332, 71);
    
    [UIView setAnimationDuration:.3];
    
    mole5.center = CGPointMake(422, 71);
    
    [UIView setAnimationDuration:.3];
    
    mole6.center = CGPointMake(102, 150);
    
    [UIView setAnimationDuration:.3];
    
    mole7.center = CGPointMake(198, 150);
    
    [UIView setAnimationDuration:.3];
    
    mole8.center = CGPointMake(291, 150);
    
    [UIView setAnimationDuration:.3];
    
    mole9.center = CGPointMake(379, 150);
    
    [UIView setAnimationDuration:.3];
    
    [UIView commitAnimations];
    
    
    
}


- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    
    UITouch *touch = [touches anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];
    
    //secret
    int se = (rand() % 20)+1;
    NSString *squeakPath = [[NSBundle mainBundle]
    pathForResource:@"squeak" ofType:@"wav"];
    
    NSURL *squeakURL = [NSURL fileURLWithPath:squeakPath];
    SystemSoundID squeakSoundID;
    AudioServicesCreateSystemSoundID((CFURLRef)squeakURL, &squeakSoundID);
    
    //sound
    NSString *squishPath = [[NSBundle mainBundle] 
                            pathForResource:@"smack" ofType:@"wav"];
    NSURL *squishURL = [NSURL fileURLWithPath:squishPath];
    SystemSoundID squishSoundID;
    AudioServicesCreateSystemSoundID((CFURLRef)squishURL, &squishSoundID);
    
    CGRect mole1Rect = [[[mole1 layer] presentationLayer] frame];
    if(mole1active)
    {
        if(CGRectContainsPoint(mole1Rect, touchLocation))
        {
            mole1active = NO;
                        
            [UIView animateWithDuration:0.1 
                                  delay:0.0 
                                options:UIViewAnimationCurveEaseOut
                             animations:^{                             
                             } 
                             completion:^(BOOL finished) {  
                                 [UIView animateWithDuration:.1 
                                                       delay:0.0 
                                                     options:0
                                                  animations:^{                      
                                                      mole1.alpha = 0.0;
                                                  } completion:^(BOOL finished) {
                                                      
                                                  }];                 
                             }];
            
            if(se!=5)
            AudioServicesPlaySystemSound(squishSoundID);
            else
            {
                AudioServicesPlaySystemSound(squeakSoundID);
                points +=5;
            }
            
            
            points += 5;
            CurrentPoint.text = [NSString stringWithFormat:@"%d Pts", points];
            
            return;
        }
        
    }
   
    
   
    
    CGRect mole2Rect = [[[mole2 layer] presentationLayer] frame];
    if(mole2active)
    {
        if(CGRectContainsPoint(mole2Rect, touchLocation))
        {
            mole2active = NO;
            
            [UIView animateWithDuration:0.1 
                                  delay:0.0 
                                options:UIViewAnimationCurveEaseOut
                             animations:^{                              
                                 
                             } 
                             completion:^(BOOL finished) {  
                                 [UIView animateWithDuration:.1 
                                                       delay:0.0 
                                                     options:0
                                                  animations:^{                      
                                                      mole2.alpha = 0.0;
                                                  } completion:^(BOOL finished) {
                                                      
                                                  }];                 
                             }];
            
            
            //AudioServicesPlaySystemSound(squishSoundID);
            if(se!=5)
            {
                AudioServicesPlaySystemSound(squishSoundID);
            }
            else
            {
                AudioServicesPlaySystemSound(squeakSoundID);
                points +=5;
            }
            
            
            
            points += 5;
            CurrentPoint.text = [NSString stringWithFormat:@"%d Pts", points];
                    
            return;
        }
        
    }
    
    CGRect mole3Rect = [[[mole3 layer] presentationLayer] frame];
    if(mole3active)
    {
        if(CGRectContainsPoint(mole3Rect, touchLocation))
        {
            mole3active = NO;
                  
            [UIView animateWithDuration:0.1 
                                  delay:0.0 
                                options:UIViewAnimationCurveEaseOut
                             animations:^{                              
                                
                             } 
                             completion:^(BOOL finished) {  
                                 [UIView animateWithDuration:.1 
                                                       delay:0.0 
                                                     options:0
                                                  animations:^{                      
                                                      mole3.alpha = 0.0;
                                                  } completion:^(BOOL finished) {
                                                   
                                                  }];                 
                             }];
            
            
            //AudioServicesPlaySystemSound(squishSoundID);
            if(se!=5)
                AudioServicesPlaySystemSound(squishSoundID);
            else
            {
                AudioServicesPlaySystemSound(squeakSoundID);
                points +=5;
            }
            
            
            
            points += 5;
            CurrentPoint.text = [NSString stringWithFormat:@"%d Pts", points];
             
            return;
        }
        
    }
    
    CGRect mole4Rect = [[[mole4 layer] presentationLayer] frame];
    if(mole4active)
    {
        if(CGRectContainsPoint(mole4Rect, touchLocation))
        {
            mole4active = NO;
                      
            [UIView animateWithDuration:0.1 
                                  delay:0.0 
                                options:UIViewAnimationCurveEaseOut
                             animations:^{                              
                                
                             } 
                             completion:^(BOOL finished) {  
                                 [UIView animateWithDuration:.1 
                                                       delay:0.0 
                                                     options:0
                                                  animations:^{                      
                                                      mole4.alpha = 0.0;
                                                  } completion:^(BOOL finished) {
                                                  }];                 
                             }];
            
            
            //AudioServicesPlaySystemSound(squishSoundID);
            if(se!=5)
                AudioServicesPlaySystemSound(squishSoundID);
            else
            {
                AudioServicesPlaySystemSound(squeakSoundID);
                points +=5;
            }
            
            points += 5;
            CurrentPoint.text = [NSString stringWithFormat:@"%d Pts", points];
            
            return;
        }
        
    }
    
    CGRect mole5Rect = [[[mole5 layer] presentationLayer] frame];
    if(mole5active)
    {
        if(CGRectContainsPoint(mole5Rect, touchLocation))
        {
            mole5active = NO;
                       
            [UIView animateWithDuration:0.1 
                                  delay:0.0 
                                options:UIViewAnimationCurveEaseOut
                             animations:^{                              
                          
                             } 
                             completion:^(BOOL finished) {  
                                 [UIView animateWithDuration:.1 
                                                       delay:0.0 
                                                     options:0
                                                  animations:^{                      
                                                      mole5.alpha = 0.0;
                                                  } completion:^(BOOL finished) {
                                               
                                                  }];                 
                             }];
            
            
            //AudioServicesPlaySystemSound(squishSoundID);
            if(se!=5)
                AudioServicesPlaySystemSound(squishSoundID);
            else
            {
                AudioServicesPlaySystemSound(squeakSoundID);
                points +=5;
            }
            
            
            
            points += 5;
            CurrentPoint.text = [NSString stringWithFormat:@"%d Pts", points];
                       
            return;
        }
        
    }
    
    CGRect mole6Rect = [[[mole6 layer] presentationLayer] frame];
    if(mole6active)
    {
        if(CGRectContainsPoint(mole6Rect, touchLocation))
        {
            mole6active = NO;
                    
            [UIView animateWithDuration:0.1 
                                  delay:0.0 
                                options:UIViewAnimationCurveEaseOut
                             animations:^{                              
                            
                             } 
                             completion:^(BOOL finished) {  
                                 [UIView animateWithDuration:.1 
                                                       delay:0.0 
                                                     options:0
                                                  animations:^{                      
                                                      mole6.alpha = 0.0;
                                                  } completion:^(BOOL finished) {
                                                
                                                  }];                 
                             }];
            
            
            //AudioServicesPlaySystemSound(squishSoundID);
            if(se!=5)
                AudioServicesPlaySystemSound(squishSoundID);
            else
            {
                AudioServicesPlaySystemSound(squeakSoundID);
                points +=5;
            }
            
            
            
            points += 5;
            CurrentPoint.text = [NSString stringWithFormat:@"%d Pts", points];
                  
            return;
        }
        
    }
    
    CGRect mole7Rect = [[[mole7 layer] presentationLayer] frame];
    if(mole7active)
    {
        if(CGRectContainsPoint(mole7Rect, touchLocation))
        {
            mole7active = NO;
                        
            [UIView animateWithDuration:0.1 
                                  delay:0.0 
                                options:UIViewAnimationCurveEaseOut
                             animations:^{                              
                            
                             } 
                             completion:^(BOOL finished) {  
                                 [UIView animateWithDuration:.1 
                                                       delay:0.0 
                                                     options:0
                                                  animations:^{                      
                                                      mole7.alpha = 0.0;
                                                  } completion:^(BOOL finished) {
                                            
                                                  }];                 
                             }];
            
            
            //AudioServicesPlaySystemSound(squishSoundID);
            if(se!=5)
                AudioServicesPlaySystemSound(squishSoundID);
            else
            {
                AudioServicesPlaySystemSound(squeakSoundID);
                points +=5;
            }
            
            
            points += 5;
            CurrentPoint.text = [NSString stringWithFormat:@"%d Pts", points];
            
            return;
        }
        
    }
    
    CGRect mole8Rect = [[[mole8 layer] presentationLayer] frame];
    if(mole8active)
    {
        if(CGRectContainsPoint(mole8Rect, touchLocation))
        {
            mole8active = NO;
              
            [UIView animateWithDuration:0.1 
                                  delay:0.0 
                                options:UIViewAnimationCurveEaseOut
                             animations:^{                              
                            
                             } 
                             completion:^(BOOL finished) {  
                                 [UIView animateWithDuration:.1 
                                                       delay:0.0 
                                                     options:0
                                                  animations:^{                      
                                                      mole8.alpha = 0.0;
                                                  } completion:^(BOOL finished) {
                                            
                                                  }];                 
                             }];
            
            
            //AudioServicesPlaySystemSound(squishSoundID);
            if(se!=5)
                AudioServicesPlaySystemSound(squishSoundID);
            else
            {
                AudioServicesPlaySystemSound(squeakSoundID);
                points +=5;
            }
            
            
            
            points += 5;
            CurrentPoint.text = [NSString stringWithFormat:@"%d Pts", points];
             
            return;
        }
        
    }
    
    CGRect mole9Rect = [[[mole9 layer] presentationLayer] frame];
    if(mole9active)
    {
        if(CGRectContainsPoint(mole9Rect, touchLocation))
        {
            mole9active = NO;
                   
            [UIView animateWithDuration:0.1 
                                  delay:0.0 
                                options:UIViewAnimationCurveEaseOut
                             animations:^{                              
                           
                             } 
                             completion:^(BOOL finished) {  
                                 [UIView animateWithDuration:.1 
                                                       delay:0.0 
                                                     options:0
                                                  animations:^{                      
                                                      mole9.alpha = 0.0;
                                                  } completion:^(BOOL finished) {
                                    
                                                  }];                 
                             }];
            
            
            //AudioServicesPlaySystemSound(squishSoundID);
            if(se!=5)
                AudioServicesPlaySystemSound(squishSoundID);
            else
            {
                AudioServicesPlaySystemSound(squeakSoundID);
                points += 5;
            }
            
            
            
            points += 5;
            CurrentPoint.text = [NSString stringWithFormat:@"%d Pts", points];
                   
            return;
        }
        
    }
    
    
    }



@end
